package nio;


import java.nio.ByteBuffer;

/**
 * 缓冲区nio 提供给传输文件和通道一起配合使用，存储数据
 * Buffer
 * ByteBuffer
 * LongBuffer
 * IntegerBuffer
 * FloatBuffer
 * DoubleBuffer
 * **/
public class Demo1 {

    /**
     * position 缓冲区正在操作的位置 默认从0开始
     * limit 界面(缓冲区可用大小)
     * capacity 缓冲区最大容量，一旦声明不能改变
     *
     * 核心方法
     * put() 往buff存放数据
     * get() 获取数据
     * */
    public static void main(String[] args) {

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        System.out.println(byteBuffer.position()); //0
        System.out.println(byteBuffer.limit());    //1024
        System.out.println(byteBuffer.capacity()); //1024

        System.out.println("----------往bytebuff存放数据....----------");
        byteBuffer.put("libofei".getBytes());//存入7个字节
        System.out.println(byteBuffer.position()); //7
        System.out.println(byteBuffer.limit());    //1024
        System.out.println(byteBuffer.capacity()); //1024

        System.out.println("----------读取值...----------");
        byteBuffer.flip();//开启读取模式
        System.out.println(byteBuffer.position());//0，当前读的指针为0
        //当开启读取模式时，为防止误操作，会禁止写操作，可用字节为当前所用的字节
        System.out.println(byteBuffer.limit());//7
        System.out.println(byteBuffer.capacity());//1024
        System.out.println((char) byteBuffer.get());//1024
        System.out.println((char)byteBuffer.get());//1024
        System.out.println((char)byteBuffer.get());//1024
        System.out.println((char)byteBuffer.get());//1024
        System.out.println((char)byteBuffer.get());//1024
        byteBuffer.rewind();//重复读取
        System.out.println(byteBuffer.limit());//7
        byte[] bytes = new byte[byteBuffer.limit()];
        byteBuffer.get(bytes);
        System.out.println(new String(bytes,0,bytes.length));


        System.out.println("------重复读取----------");
        byteBuffer.rewind();//重复读取
        System.out.println(byteBuffer.position());
        System.out.println(byteBuffer.limit());
        System.out.println(byteBuffer.capacity());
        byte[] bytes2 = new byte[byteBuffer.limit()];
        byteBuffer.get(bytes2);
        System.out.println(new String(bytes2,0,bytes2.length));

        //清空缓冲数据被遗忘值
        System.out.println("------清空缓冲区-----");
        byteBuffer.clear();
        System.out.println(byteBuffer.position());
        System.out.println(byteBuffer.capacity());
        System.out.println((char)byteBuffer.get());
    }







}
